package com.have.blog.admin.config;

import com.have.blog.admin.service.AdminLoginService;
import com.have.blog.admin.service.AdminResourceMenuService;
import com.have.blog.base.constant.BaseConstant;
import com.have.blog.model.models.Admin;
import com.have.blog.model.models.ResourceMenu;
import com.have.blog.security.component.DynamicSecurityService;
import com.have.blog.security.config.BaseSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends BaseSecurityConfig {

    @Autowired
    private AdminLoginService adminLoginService;
    @Autowired
    private AdminResourceMenuService resourceMenuService;

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            Admin admin = adminLoginService.loadAdminByUsername(username);
            return adminLoginService.loadUserDetailByAdmin(admin);
        };
    }

    /**
     * 获取系统全部资源
     * @return
     */
    @Bean
    public DynamicSecurityService dynamicSecurityService() {
        return new DynamicSecurityService() {
            @Override
            public Map<String, ConfigAttribute> loadDataSource() {
                ConcurrentHashMap<String, ConfigAttribute> map = new ConcurrentHashMap<>();

                List<ResourceMenu> categoryMenus = resourceMenuService.getAll();
                for (ResourceMenu categoryMenu : categoryMenus) {
                    map.put(categoryMenu.getUrl(), new org.springframework.security.access.SecurityConfig(categoryMenu.getName() + BaseConstant.SYMBOL_COLON + categoryMenu.getSummary()));
                }
                return map;
            }
        };
    }
}

